import pandas as pd
import os
import logging

logger = logging.getLogger('django')
# 全局变量存储CSV数据和读取状态
_csv_data = None
_current_index = 0
_total_rows = 0
_column_indices = {}
_end_reached = False  # 标记是否已到达数据末尾

def load_csv_data(csv_path='data.csv'):
    global _csv_data, _current_index, _total_rows, _column_indices, _end_reached

    try:
        if not os.path.exists(csv_path):
            logger.error(f"CSV文件不存在: {csv_path}")
            return [], {}
        #logger.info(f"加载CSV文件: {csv_path}")
        df = pd.read_csv(csv_path, encoding='GBK')
        _column_indices = {
            'BatSOC': _find_column_index(df, ['BatSOC', 'SOC', '电池SOC']),
            'ChaEne': _find_column_index(df, ['ChaEne', 'ChargeEnergy', '充电能量']),
            'BatOverChaTime': _find_column_index(df, ['BatOverChaTime', 'OverChargeTime', '过充时间']),
            'ChaTime': _find_column_index(df, ['ChaTime', 'ChargeTime', '充电时间'])
        }
        _csv_data = df.iloc[::-1].values.tolist()  # 倒序存储
        _total_rows = len(_csv_data)
        _current_index = 0
        _end_reached = False  # 重置结束标记
        return _csv_data,_column_indices

    except Exception as e:
        print(f"加载CSV文件失败: {e}")
        return False


def _find_column_index(df, possible_names):
    for name in possible_names:
        if name in df.columns:
            return df.columns.get_loc(name)
    return -1


def is_data_end():
    """检查是否已到达数据末尾"""
    return _end_reached


def get_next_data():
    global _current_index, _end_reached

    # 当数据为空或已读取完毕
    if not _csv_data or _current_index >= _total_rows:
        _end_reached = True  # 标记数据已结束
        return 0.0, 0.0, 0, 0

    try:
        row = _csv_data[_current_index]
        bat_soc = float(row[_column_indices['BatSOC']]) if _column_indices['BatSOC'] != -1 else 0.0
        cha_ene = float(row[_column_indices['ChaEne']]) if _column_indices['ChaEne'] != -1 else 0.0
        bat_over_cha_time = int(row[_column_indices['BatOverChaTime']]) if _column_indices[
                                                                               'BatOverChaTime'] != -1 else 0
        cha_time = int(row[_column_indices['ChaTime']]) if _column_indices['ChaTime'] != -1 else 0

        _current_index += 1

        # 检查是否到达数据末尾
        if _current_index >= _total_rows:
            _end_reached = True

        return bat_soc, cha_ene, bat_over_cha_time, cha_time
    except Exception as e:
        print(f"读取数据错误: {e}")
        return 0.0, 0.0, 0, 0

#load_csv_data(csv_path="data.csv")
#get_next_data()